//
//  CoverView.m
//  JDong
//
//  Created by liu nian on 13-12-12.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "CoverView.h"
#import "MKImageView.h"
#import "AdItem.h"
#import "CSCoverStoryManager.h"
#import <QuartzCore/QuartzCore.h>
#import "UIImageView+WebCache.h"
#import "CSCoverStoryManager.h"
#import "DataEnvironment.h"
#import "MainViewController.h"
#import "ADWebViewController.h"

#define kTagStoryView   102121
static const int kIntAnimationInterval = 30;
static const int kIntSwitchImageInterval = kIntAnimationInterval+3;
static const int kIntSwitchActionDuration = 2;

@interface CoverView ()<CSCoverStoryManagerDelegate>{
    CGPoint   _startPoint;
    NSInteger _coverIndex;
}

@property (nonatomic, retain) UIView *imageViewFrame;
@property (nonatomic, retain) MKImageView *imageView;
@property (nonatomic, retain) MKImageView *nextImageView;
@property (nonatomic, retain) AdItem   *curAdItem;
@property (nonatomic, retain) UIImageView *arrowImageView;
@property (nonatomic, retain) UIView *storyView;

- (void)showArrow;
- (void)startAnimation;
- (void)stopAnimation;
- (void)selectNextImage;
- (void)resetNextImageFrame;
- (void)switchImageActionDone;

- (void)showCoverImage;

- (void)storyButtonTapped:(id)sender;
@end

@implementation CoverView

- (void)dealloc{
    [[CSCoverStoryManager sharedManager] removeObserver:self];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setBackgroundColor:[UIColor blackColor]];
        _showDefault = NO;
        _coverIndex = 0;
        
        [[CSCoverStoryManager sharedManager] addObserver:self];
        [[CSCoverStoryManager sharedManager] requestAD];
        [self showCoverImage];
        
        [self performSelector:@selector(showArrow) withObject:nil afterDelay:1.0f];
        
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
}

- (void)showArrow {
    [self.arrowImageView startAnimating];
	self.arrowImageView.alpha = 0;
	self.arrowImageView.layer.transform = CATransform3DMakeScale(2.0, 2.0, 1.0);
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:1];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	self.arrowImageView.alpha = 1;
	self.arrowImageView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 1.0);
	[UIView commitAnimations];
}

#pragma mark - Image Animation
- (void)startImageSwitch {
    if (!self.imageView.adItem) {
        if (self.frame.origin.x == 0) {
            [self startAnimation];
        }
    }
    
    INVALIDATE_TIMER(_switchTimer);
    _switchTimer = [NSTimer scheduledTimerWithTimeInterval:5
                                                    target:self
                                                  selector:@selector(selectNextImage)
                                                  userInfo:nil
                                                   repeats:NO];
}

- (void)stopImageSwitch {
    if (!self.imageView.adItem) {
        [self stopAnimation];
    }
    INVALIDATE_TIMER(_switchTimer);
}

- (void)startAnimation {
    CGSize size;
    size.width = self.imageView.frame.size.width;
    size.height = self.imageView.frame.size.height;
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, _startPoint.x,_startPoint.y);
    if (fabs(_startPoint.x-self.bounds.size.width/2)>10.0 ||
        fabs(_startPoint.y-self.bounds.size.height/2)>10.0) {
        CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    }
    _startPoint = CGPointMake(floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    
    CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width-size.width/2), floor(self.bounds.size.height-size.height/2));
    CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width-size.width/2), size.height/2);
    CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    CGPathAddLineToPoint(path, NULL, floor(size.width/2), floor(self.bounds.size.height-size.height/2));
    CGPathAddLineToPoint(path, NULL, floor(size.width/2), floor(size.height/2));
    CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [pathAnimation setPath:path];
    pathAnimation.duration = kIntAnimationInterval;
    pathAnimation.removedOnCompletion = YES;
    CFRelease(path);
    [self.imageView.layer addAnimation:pathAnimation forKey:@"CoverPositionAnimation"];
    
    self.imageView.layer.position = CGPointMake(floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
}

- (void)stopAnimation {
    if ([self.imageView.layer animationForKey:@"CoverPositionAnimation"]) {
        _startPoint = [(CALayer *)[self.imageView.layer presentationLayer] position];
        [self.imageView.layer removeAnimationForKey:@"CoverPositionAnimation"];
        
        self.imageView.layer.position = _startPoint;
    }
}

#pragma mark - Image Switch
- (void)resetNextImageFrame
{
    CGFloat maxScaleH = 1.5f;
    CGFloat maxScaleV = 1.4f;
    CGFloat scale = 1.1f;
    
    CGSize size = self.nextImageView.image.size;
    //    if (size.width > self.bounds.size.width*scale && size.height > self.bounds.size.height*scale)
    {
    CGFloat ratio1 = (self.bounds.size.width*scale)/size.width;
    CGFloat ratio2 = (self.bounds.size.height*scale)/size.height;
    if (ratio1 > ratio2) {
        size.width = size.width*ratio1;
        size.height = size.height*ratio1;
        if (size.height > self.bounds.size.height*maxScaleV) {
            size.height = self.bounds.size.height*maxScaleV;
        }
    } else {
        size.width = size.width*ratio2;
        size.height = size.height*ratio2;
        if (size.width > self.bounds.size.width*maxScaleH) {
            size.width = self.bounds.size.width*maxScaleH;
        }
    }
    }
    self.nextImageView.frame = CGRectMake(0, 0, size.width, size.height);
    self.nextImageView.center = self.imageViewFrame.center;
}


static inline UIViewAnimationOptions animationOptionsWithCurve(UIViewAnimationCurve curve)
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
    }
}


- (void)switchImageAction {
    [self stopAnimation];
    _startPoint = CGPointMake(floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    
	//图片切换动画
    self.nextImageView.alpha = 0.0f;
	_imageView.alpha = 1.0f;
    
    UIView *oldStoryView = [self viewWithTag:kTagStoryView];
    
    self.storyView.alpha = 0.0f;
    [self addSubview:self.storyView];
    [self bringSubviewToFront:_arrowImageView];
    [UIView animateWithDuration:kIntSwitchActionDuration
                          delay:0.0
                        options:animationOptionsWithCurve(UIViewAnimationCurveEaseInOut)
                     animations:^{
                         self.nextImageView.alpha = 1.0f;
                         self.storyView.alpha = 0.7f;
                         self.imageView.alpha = 0.0f;
                         oldStoryView.alpha = 0.0f;
                     }
                     completion:^(BOOL finished) {
                         [oldStoryView removeFromSuperview];
                         self.storyView = nil;
                         [self switchImageActionDone];
                     }];
}

- (void)switchImageActionDone {
	
    MKImageView *tmp = self.imageView;
    self.imageView = self.nextImageView;
    self.nextImageView = tmp;
    
    if (!_imageView.adItem) {
        if (self.frame.origin.x == 0) {
            [self startAnimation];
        }
    }
    
    NSTimeInterval interval = kIntSwitchImageInterval;
    if (_imageView.adItem) {
        interval = floor(kIntSwitchImageInterval/2);
    } else if (_showDefault) {
        interval = 5;
    }
    _switchTimer = [NSTimer scheduledTimerWithTimeInterval:interval
                                                    target:self
                                                  selector:@selector(selectNextImage)
                                                  userInfo:nil
                                                   repeats:NO];
    
}

- (void)selectNextImage
{
    INVALIDATE_TIMER(_switchTimer);
    self.curAdItem = nil;
    
    if (!_imageView || !_imageView.image) {
        self.nextImageView.adItem = nil;
        BOOL isIphone5 = self.frame.size.height > 480;
        UIImage *image = IMGNAMED(@"Default.png");
        if (isIphone5) {
            image = IMGNAMED(@"cover.jpg");
        }
        self.nextImageView.image = image;
        [self resetNextImageFrame];
        _showDefault = YES;
        [self switchImageAction];
        
        return;
    }
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    if ([CSCoverStoryManager sharedManager].ads) {
        [array addObjectsFromArray:[CSCoverStoryManager sharedManager].ads];
    }
    
    if ([array count] == 0) {
        if (!_showDefault) {
            self.nextImageView.adItem = nil;
            BOOL isIphone5 = self.frame.size.height > 480;
            UIImage *image = IMGNAMED(@"Default.png");
            if (isIphone5) {
                image = IMGNAMED(@"cover.jpg");
            }
            self.nextImageView.image = image;
            [self resetNextImageFrame];
            _showDefault = YES;
            [self switchImageAction];
        } else {
            _switchTimer = [NSTimer scheduledTimerWithTimeInterval:kIntSwitchImageInterval
                                                            target:self
                                                          selector:@selector(selectNextImage)
                                                          userInfo:nil
                                                           repeats:NO];
        }
        
    } else {
        
        if (_coverIndex >=[array count] || _coverIndex < 0) {
            _coverIndex = 0;
        }
        
        NSObject *object = [array objectAtIndex:_coverIndex];
        
        if ([object isKindOfClass:[AdItem class]]) {
            AdItem *adItem = (AdItem *)object;
            self.nextImageView.adItem = adItem;
            self.curAdItem = adItem;
            
            __block CoverView *weatherView = self;
            [self.nextImageView setImageWithURL:[NSURL URLWithString:adItem.adUrl] placeholderImage:IMGNAMED(@"") completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                if (image) {
                    [weatherView doneFinishImage];
                }
                
                if (error) {
                    [weatherView performSelector:@selector(selectNextImage) withObject:nil afterDelay:10.0f];
                }
                
            }];
        }
        
        _coverIndex++;
    }
}

- (void)doneFinishImage{
    _showDefault = NO;
    if ([_imageView adItem]) {
        _nextImageView.frame = self.imageViewFrame.bounds;
    } else {
        [self resetNextImageFrame];
    }
    [self switchImageAction];
}

#pragma mark - Show AD
- (void)showCoverImage
{
    [self selectNextImage];
}

#pragma mark CSCoverStoryManagerDelegate
- (void)mkManagerAllAdsRequestDidFinishedWithAds:(NSArray *)ads{
    _coverIndex = 0;
    [self selectNextImage];
}


#pragma mark - UIButton method
- (void)storyButtonTapped:(id)sender {
    if (self.curAdItem) {
        NSString *clickTypeStr = @"";
        if (self.curAdItem.clickType == MKAdClickTypeApp) {
            clickTypeStr = @"App";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.curAdItem.clickUrl]];
            
        } else if (self.curAdItem.clickType == MKAdClickTypeUrl) {
            clickTypeStr = @"Url";
            if (self.curAdItem.clickUrl) {
                ADWebViewController *webViewController = [[ADWebViewController alloc] initWithURL:[NSURL URLWithString:self.curAdItem.clickUrl]];
//                [[DataEnvironment sharedDataEnvironment].navController presentModalViewController:webViewController
//                                                                                         animated:YES];
                [[DataEnvironment sharedDataEnvironment].navController presentViewController:webViewController animated:YES completion:^{
                    [[DataEnvironment sharedDataEnvironment].mainViewController hideCover];
                }];
                
            }
        }
        
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.curAdItem.title, @"title",self.curAdItem.clickUrl, @"clickUrl",clickTypeStr,@"clickType", nil];
        [MobClick event:@"coverClick" attributes:dict];
    }
}

#pragma mark setter
#define kShadowOffset CGSizeMake(0, 1.0)

- (UIView *)storyView {
    
    if (!self.curAdItem || !self.curAdItem.title || [self.curAdItem.title length] == 0) {
        return nil;
    }
    
    if (!_storyView) {
        _storyView = [[UIView alloc] initWithFrame:CGRectMake(floor((self.bounds.size.width-320)/2),
                                                              self.bounds.size.height-40,
                                                              320.0f, 40.0f)];
        _storyView.backgroundColor = [UIColor blackColor];
        _storyView.alpha = 0.6;
        _storyView.tag = kTagStoryView;
        _storyView.clipsToBounds = YES;
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.numberOfLines = 1;
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = COLOR_RGB(255.0,254.0,254.0);
        titleLabel.font = FONT_CONTENT(18.0);
        NSString *title = self.curAdItem.title;
        if ([title length]>25) {
            title = [title substringToIndex:25];
            title = [NSString stringWithFormat:@"%@...",title];
        }
        titleLabel.text = title;
        CGSize size = [titleLabel sizeThatFits:CGSizeMake(_storyView.bounds.size.width-10, CGFLOAT_MAX)];
        titleLabel.frame = CGRectMake(10, 10, size.width,20);
        [_storyView addSubview:titleLabel];
        
        UIButton *storyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        storyButton.backgroundColor = [UIColor clearColor];
        [storyButton setBackgroundImage:IMGNAMED(@"bg_button_highlighted.png") forState:UIControlStateHighlighted];
        storyButton.frame = _storyView.bounds;
        [_storyView addSubview:storyButton];
        [_storyView sendSubviewToBack:storyButton];
        [storyButton addTarget:self action:@selector(storyButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _storyView;
}

- (MKImageView *)imageView {
    if (!_imageView) {
        _imageView = [[MKImageView alloc] initWithFrame:self.imageViewFrame.bounds];
        _imageView.backgroundColor = [UIColor clearColor];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [self.imageViewFrame addSubview:_imageView];
    }
    return _imageView;
}

- (MKImageView *)nextImageView
{
    if (!_nextImageView) {
        _nextImageView = [[MKImageView alloc] initWithFrame:self.imageViewFrame.bounds];
        _nextImageView.backgroundColor = [UIColor clearColor];
        _nextImageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [self.imageViewFrame addSubview:_nextImageView];
    }
    return _nextImageView;
}


- (UIView *)imageViewFrame {
    if (!_imageViewFrame) {
        _imageViewFrame = [[UIView alloc] initWithFrame:self.bounds];
        _imageViewFrame.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _imageViewFrame.backgroundColor = [UIColor clearColor];
        _imageViewFrame.clipsToBounds = YES;
        [self addSubview:_imageViewFrame];
        [self sendSubviewToBack:_imageViewFrame];
    }
    return _imageViewFrame;
}

- (UIImageView *)arrowImageView {
    if (!_arrowImageView) {
        _arrowImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        UIImage *image = IMGNAMED(@"icon_arrow1.png");
        _arrowImageView.frame = CGRectMake(self.bounds.size.width-image.size.width,
                                           self.bounds.size.height-image.size.height-100,
                                           image.size.width, image.size.height);
        NSArray *imageArr = [NSArray arrayWithObjects:
                             IMGNAMED(@"icon_arrow1.png"),
                             IMGNAMED(@"icon_arrow2.png"),
                             IMGNAMED(@"icon_arrow3.png"),
                             IMGNAMED(@"icon_arrow4.png"),
                             IMGNAMED(@"icon_arrow5.png"),
                             IMGNAMED(@"icon_arrow6.png"),
                             IMGNAMED(@"icon_arrow7.png"),
                             IMGNAMED(@"icon_arrow8.png"),
                             IMGNAMED(@"icon_arrow9.png"),
                             IMGNAMED(@"icon_arrow10.png"),
                             nil];
        _arrowImageView.animationImages = imageArr;
        _arrowImageView.animationDuration = 1.5f;
        [self addSubview:_arrowImageView];
    }
    return _arrowImageView;
}
@end
